//创建用户小仓库
import { defineStore } from 'pinia';
//引入接口
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user';
//引入数据类型
import type {
  loginFormData,
  loginResponseData,
  userInfoReponseData,
} from '@/api/user/type';
import type { UserState } from './types/type';
//导入操作本地存储的方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token';

//引入常量路由
import { constantRoute, asyncRoute, anyRoute } from '@/router/routes';

//引入路由
import router from '@/router';

//引入深拷贝方法
//@ts-ignore
import cloneDeep from 'lodash/cloneDeep';

//过滤当前用户需要展示的异步路由
function filterAsyncRoute(asyncRoute: any, routes: any) {
  return asyncRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      //还有子路由就递归
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes);
      }
      return true;
    }
  });
}

let useUserStore = defineStore('user', {
  //存储数据
  state: (): UserState => {
    return {
      token: GET_TOKEN(),
      menuRoutes: constantRoute, //生成菜单需要的数组
      username: '',
      avatar: '',
      //用户所有的按钮权限
      buttons: [],
    };
  },
  //异步、逻辑
  actions: {
    //用户登录
    async userLogin(data: loginFormData) {
      let res: loginResponseData = await reqLogin(data);
      if (res.code === 200) {
        this.token = res.data as string;
        //持久化存储token
        SET_TOKEN(res.data as string);
        //更新promise状态
        return 'ok';
      } else {
        return Promise.reject(new Error(res.data));
      }
    },
    //获取用户信息
    async userInfo() {
      let res: userInfoReponseData = await reqUserInfo();
      if (res.code === 200) {
        this.username = res.data.name;
        this.avatar = res.data.avatar;
        this.buttons = res.data.buttons;

        //计算当前用户要展示的异步路由  --深拷贝避免影响到之后登陆
        let userAsyncRoute = filterAsyncRoute(
          cloneDeep(asyncRoute),
          res.data.routes,
        );
        //加上常量和任意路由 结果就是菜单的数据
        this.menuRoutes = [...constantRoute, ...userAsyncRoute, ...anyRoute];
        //手动注册异步和任意路由
        [...userAsyncRoute, ...anyRoute].forEach((route: any) => {
          router.addRoute(route);
        });
        return 'ok';
      } else {
        return Promise.reject('获取用户信息失败');
      }
    },
    //退出登录
    async userLogout() {
      let res: any = await reqLogout(); //
      if (res.code === 200) {
        this.token = '';
        this.username = '';
        this.avatar = '';
        REMOVE_TOKEN();
        return 'ok';
      } else {
        return Promise.reject(new Error(res.message));
      }
    },
  },
  getters: {},
});

export default useUserStore;
